﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using System.Reflection;
using System.ComponentModel.DataAnnotations;

namespace Toolkit.Web.Mvc.Validation
{
    [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)]
    public class EqualToPropertyAttribute : ValidationAttribute, IDependentFieldModelValidationAttribute
    {
        public EqualToPropertyAttribute(string dependentPropertyName)
        {
            DependentPropertyName = dependentPropertyName;
        }

        public string DependentPropertyName
        {
            get;
            set;
        }

        public override bool IsValid(object value)
        {
            // Work done in other IsValid method.
            return true;
        }

        public bool IsValid(ControllerContext controllerContext, object model, ModelMetadata modelMetadata)
        {
            PropertyInfo dependentPropertyInfo = model.GetType().GetProperty(DependentPropertyName);

            if (dependentPropertyInfo == null)
            {
                throw new InvalidOperationException("Unknown property: " + DependentPropertyName);
            }

            object dependentPropertyValue = dependentPropertyInfo.GetGetMethod().Invoke(model, null);

            return (
                (modelMetadata.Model == null && dependentPropertyValue == null) ||
                (modelMetadata.Model != null && dependentPropertyValue != null && modelMetadata.Model.Equals(dependentPropertyValue))
            );
        }
    }
}
